<!DOCTYPE html>
<html>
<head>
  <title>Controlling A Sprite</title>
  <script src="../../kontra.js"></script>
</head>
<body>
  <canvas id="game" width="600" height="400" style="background: #333331"></canvas>
  <script id="code">
    // initialize the game and setup the canvas
    let { canvas, context } = kontra.init();

    kontra.initKeys();

    // create a basic sprite with a velocity
    window.sprite = kontra.Sprite({
      x: 290,
      y: 180,
      dx: 3,
      dy: 3,
      width: 20,
      height: 40,
      color: 'red',
      // pass a custom update function to the sprite
      update: function() {
        // move the sprite with the keyboard
        if (kontra.keyPressed('arrowup')) {
          this.y -= this.dy;
        }
        else if (kontra.keyPressed('arrowdown')) {
          this.y += this.dy;
        }

        if (kontra.keyPressed('arrowleft')) {
          this.x -= this.dx;
        }
        else if (kontra.keyPressed('arrowright')) {
          this.x += this.dx;
        }
      }
    });

    // prevent default key behavior
    kontra.onKey(['arrowup', 'arrowdown', 'arrowleft', 'arrowright'], function(e) {
      e.preventDefault();
    });

    // clamp sprites movement to the game between x1, y1, and x2, y2
    sprite.position.clamp(0, 0, canvas.width - sprite.width, canvas.height - sprite.height);

    // create the game loop to update and render the sprite
    window.loop = kontra.GameLoop({
      update: function() {
        sprite.update();
      },
      render: function() {
        sprite.render();
      }
    });

    // start the loop
    loop.start();
  </script>
  <script src="../prism/codeOutput.js"></script>
</body>
</html>